package com.cyzy.controller;
import com.alibaba.fastjson.JSON;
import com.cyzy.dto.ForgetDto;
import com.cyzy.dto.PayPwdDto;
import com.cyzy.dto.Result;
import com.cyzy.pojo.User;
import com.cyzy.pojo.Payment;
import com.cyzy.service.UserService;
import com.cyzy.utils.Md5Util;
import com.cyzy.utils.RedisUtils;
import com.cyzy.utils.TokenUtils;
import org.cyzy.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.StringRedisTemplate;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;

/**
 * @author LIGHT
 */
@RestController
@RequestMapping("/user")
public class UserController {
    // Redis验证码前缀
    private static final String CAPTCHA_PREFIX = "captcha:";
    // 验证码有效期（秒） // 5分钟
    private static final long CAPTCHA_EXPIRATION = 300;

    @Autowired
    private CodeUtils codeUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 上传用户头像
     * @param file 用户上传的头像文件
     * @param userId 用户ID
     * @return 上传结果
     */
    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId) {
        try {
            // 检查用户是否存在
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error().message("用户不存在");
            }
            // 准备请求头和请求体
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            ByteArrayResource fileResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
            body.add("file", fileResource);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 调用上传服务
            String uploadUrl = "http://upload-service/oss/upload";
            ResponseEntity<Map> response = restTemplate.postForEntity(uploadUrl, requestEntity, Map.class);

            // 获取上传后的文件名
            if (response.getBody() != null && response.getBody().containsKey("fileName")) {
                String fileName = (String) response.getBody().get("fileName");

                // 更新用户头像信息
                boolean updateResult = userService.updateUserAvatar(userId, fileName);
                if (updateResult) {
                    return Result.ok().message("头像上传成功").data("avatarUrl", fileName);
                } else {
                    return Result.error().message("更新用户头像信息失败");
                }
            } else {
                return Result.error().message("上传服务未返回文件名");
            }
        } catch (IOException e) {
            return Result.error().message("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.error().message("上传失败: " + e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@RequestParam("username") String username, @RequestParam("password") String password,
                        @RequestParam("uuid") String uuid, @RequestParam("code") String code){
        String sessionCode = redisUtils.get(uuid);

        if (sessionCode == null || !sessionCode.trim().equals(code.trim())) {
            return Result.error().message("验证码错误或已过期");
        }

        redisUtils.del(uuid);

        User user = userService.login(username, password);
        if (user == null) {
            return Result.error().message("用户名或密码错误");
        }


        String token = tokenUtils.generateToken(user);

        redisUtils.set(token, user.getUserAcc());
        redisUtils.setExpire(token, 86400);



        return Result.ok().data("user", user).data("token", token);
    }

    /**
     * 获取验证码
     */
    @GetMapping("/getCode")
    public Result getCode(@RequestParam("uuid")String uuid) {
        // 生成验证码
        String codeBase64 = codeUtils.getRandomCodeImage();
        System.out.println("验证码："+codeUtils.getCode());

        // 将验证码存入Redis，设置过期时间
        // 键： key   值：验证码
        redisUtils.set(uuid,codeUtils.getCode());
        // 设置redis   过期时间
        redisUtils.setExpire(uuid,60*5);

        return Result.ok().data("codeBase64",codeBase64);
    }

    /**
     * 添加用户
     */
    @PostMapping("/register")
    public Result addUser(@RequestBody User user, @RequestParam("code") String code) {
        // 检查用户名是否已存在
        User existingUser = userService.getUserByUsername(user.getUserAcc());
        if (existingUser != null) {
            return Result.error().message("用户名已存在");
        }
        // 检查邮箱是否绑定
        boolean emailUsed = userService.isEmailUsed(user.getUserEmail());
        if (emailUsed) {
            return Result.error().message("邮箱已绑定其他账号，请换一个邮箱进行绑定");
        }
        // 校验验证码（从 Redis 中取出）
        String md5email = Md5Util.getMD5String(user.getUserEmail());
        String sessionCode = redisUtils.get(md5email);
        if (sessionCode == null || !sessionCode.equals(code)) {
            return Result.error().message("验证码错误或已过期");
        }

        boolean success = userService.addUser(user);
        if (success) {
            return Result.ok().message("注册成功");
        } else {
            return Result.error().message("注册失败");
        }
    }



    /**
     * 查询用户余额
     * @param userId 用户ID
     * @return 包含用户余额的结果
     */
    @GetMapping("/balance")
    public Result getUserBalance(@RequestParam("userId") Long userId) {
//        User user = userService.getById(userId);
        String cacheKey = "user:" + userId + ":balance";

        // 1. 先从缓存获取
        String cachedData = redisTemplate.opsForValue().get(cacheKey);
        if (cachedData != null) {
            User user1 = JSON.parseObject(cachedData, User.class);
            return Result.ok().data("balance",user1.getUserMoney()).data("integral",user1.getUserScore());
        }

        // 2. 缓存未命中，查询数据库
        User user = userService.getById(userId);



        if (user != null) {
            // 3. 写入缓存，设置合理过期时间

            redisTemplate.opsForValue().set(
                    cacheKey,
                    JSON.toJSONString(user),
                    30, TimeUnit.MINUTES // 根据业务设置过期时间
            );

            return Result.ok().data("balance", user.getUserMoney()).data("integral",user.getUserScore());
        } else {
            return Result.error().message("用户不存在");
        }
    }

    /**
     * 用户通过支付宝沙箱充值
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 充值结果
     */
    @PostMapping("/alipayRecharge")
    public Result alipayRecharge(@RequestParam("userId") Long userId,
                                 @RequestParam("amount") Double amount) {
        // 检查参数
        if (amount <= 0) {
            return Result.error().message("充值金额必须大于0");
        }

        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }

        try {
            System.out.println("收到用户充值请求，用户ID：" + userId + "，金额：" + amount);

            // 调用支付服务创建支付记录 - 改为调用小程序专用接口
            String paymentServiceUrl = "http://alipay-service/alipay/createOrderForMiniProgram";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("userId", userId.toString());
            map.add("amount", amount.toString());
            map.add("subject", "充值余额");

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);

            System.out.println("准备调用支付服务：" + paymentServiceUrl);

            // 调用支付服务
            ResponseEntity<Map> response = restTemplate.postForEntity(paymentServiceUrl, requestEntity, Map.class);
            Map<String, Object> responseBody = response.getBody();

            System.out.println("支付服务响应：" + responseBody);

            if (responseBody != null && responseBody.containsKey("code") && (Integer)responseBody.get("code") == 200) {
                // 获取订单号和其他数据
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                String orderNo = data != null ? (String) data.get("orderNo") : "";

                return Result.ok()
                        .message("订单创建成功，请完成支付")
                        .data("orderNo", orderNo)
                        .data("amount", amount);
            } else {
                return Result.error().message("订单创建失败：" + (responseBody != null ? responseBody.get("msg") : "未知错误"));
            }
        } catch (Exception e) {
            System.err.println("创建充值订单失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error().message("创建充值订单失败：" + e.getMessage());
        }
    }

    // 获取用户的积分
    @GetMapping("/integral")
    public Result getUserIntegral(@RequestParam("userId") Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }

        // 获取用户的积分
        Integer integral = user.getUserScore();
        return Result.ok().data("integral", integral);
    }


    // 邮箱登录
    @GetMapping("/emailLogin")
    public Result login(@RequestParam("email") String email, @RequestParam("code") String code){
        String md5email = Md5Util.getMD5String(email);
        String sessionCode = redisUtils.get(md5email);
        if (sessionCode == null || !sessionCode.trim().equals(code.trim())) {
            return Result.error().message("验证码错误或已过期");
        }
        User user = userService.emailLogin(email);
        if (user == null) {
            return Result.error().message("邮箱或验证码错误");
        }
        String token = tokenUtils.generateToken(user);
        redisUtils.set(token, user.getUserAcc());
        redisUtils.setExpire(token, 86400);
        return Result.ok().data("user", user).data("token", token);
    }


    //忘记密码
    @PostMapping("/forget")
    public Result forget(@RequestBody ForgetDto forget){
        String md5Email = Md5Util.getMD5String(forget.getEmail());
        String sessionCode = redisUtils.get(md5Email);

        if (sessionCode == null || !sessionCode.trim().equals(forget.getCode().trim())) {
            return Result.error().message("验证码错误或已过期");
        }
        boolean success = userService.forget(forget.getEmail(), forget.getPassword());
        if (!success) {
            return Result.error().message("重置密码失败");
        }
        return Result.ok().message("重置密码成功");
    }

    /**
     * 获取用户头像
     * @param userId 用户ID
     * @return 包含用户头像URL的结果
     */
    @GetMapping("/avatar")
    public Result getUserAvatar(@RequestParam("userId") Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 获取用户头像名称
        String avatarFileName = user.getUserAvatar();
        if (avatarFileName == null || avatarFileName.trim().isEmpty()) {
            return Result.ok().message("用户未设置头像").data("avatarUrl", "");
        }
        
        return Result.ok().data("avatarUrl", avatarFileName);
    }

    /**
     * 修改用户昵称
     * @param userId 用户ID
     * @param nickname 新昵称
     * @return 更新结果
     */
    @PostMapping("/updateNickname")
    public Result updateNickname(@RequestParam("userId") Long userId, @RequestParam("nickname") String nickname) {
        // 检查参数
        if (nickname == null || nickname.trim().isEmpty()) {
            return Result.error().message("昵称不能为空");
        }
        
        // 检查昵称长度
        if (nickname.length() < 2 || nickname.length() > 16) {
            return Result.error().message("昵称长度应为2-16个字符");
        }
        
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 执行更新
        boolean success = userService.updateUserNickname(userId, nickname);
        if (success) {
            return Result.ok().message("昵称修改成功");
        } else {
            return Result.error().message("昵称修改失败，请稍后重试");
        }
    }

    /**
     * 查看用户是否设置了支付密码
     * @param userId 用户ID
     * @return 检查结果
     */
    @GetMapping("/checkPayPassword")
    public Result checkPayPassword(@RequestParam("userId") Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 检查是否设置了支付密码
        boolean hasPayPassword = userService.hasPayPassword(userId);
        
        return Result.ok().data("hasPayPassword", hasPayPassword);
    }

    /**
     * 设置支付密码
     */
    @PostMapping("/setPayPassword")
    public Result setPayPassword(@RequestBody PayPwdDto payPwdDto
    ) {
        // 检查用户是否存在
        User user = userService.getById(payPwdDto.getUserId());
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 检查邮箱是否匹配
        String email = payPwdDto.getEmail();
        if (!email.equals(user.getUserEmail())) {
            return Result.error().message("邮箱与用户不匹配");
        }


        
        // 验证码校验
        String md5Email = Md5Util.getMD5String(payPwdDto.getEmail());
        String storedCode = redisUtils.get(md5Email);
        System.out.println("redis的验证码: " + storedCode);
        if (storedCode == null || !storedCode.equals(payPwdDto.getCode())) {
            return Result.error().message("验证码错误或已过期");
        }

        
        // 检查支付密码格式（6位纯数字）
        String payPassword = payPwdDto.getPayPassword();
        if (!payPassword.matches("^\\d{6}$")) {
            return Result.error().message("支付密码必须为6位纯数字");
        }
        
        // 设置支付密码
        boolean success = userService.setPayPassword(payPwdDto.getUserId(), payPassword);
        
        if (success) {
            return Result.ok().message("支付密码设置成功");
        } else {
            return Result.error().message("支付密码设置失败，请稍后重试");
        }
    }

    /**
     * 判断用户是否有地址
     * @param userId 用户ID
     * @return 检查结果
     */
    @GetMapping("/checkAddress")
    public Result checkAddress(@RequestParam("userId") Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 检查用户是否有地址
        boolean hasAddress = userService.hasAddress(userId);
        
        return Result.ok().data("hasAddress", hasAddress);
    }

    /**
     * 用户充值余额接口 - 供支付宝沙箱支付成功后回调
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 充值结果
     */
    @PostMapping("/recharge")
    public Result recharge(@RequestParam("userId") Long userId, @RequestParam("amount") Double amount) {
        // 检查参数
        if (amount <= 0) {
            System.err.println("充值金额必须大于0：" + amount);
            return Result.error().message("充值金额必须大于0");
        }

        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            System.err.println("用户不存在：" + userId);
            return Result.error().message("用户不存在");
        }

        System.out.println("收到支付宝回调充值请求，用户ID：" + userId + "，金额：" + amount);
        System.out.println("用户当前余额：" + user.getUserMoney());

        // 执行充值
        boolean success = userService.rechargeBalance(userId, amount);
        if (success) {
            // 充值成功后重新获取用户信息，获取最新余额
            User updatedUser = userService.getById(userId);
            System.out.println("充值成功，用户新余额：" + updatedUser.getUserMoney());
            return Result.ok().message("充值成功").data("balance", updatedUser.getUserMoney());
        } else {
            System.err.println("充值失败，请稍后重试");
            return Result.error().message("充值失败，请稍后重试");
        }
    }

    /**
     * 小程序环境直接发起支付宝支付
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 支付结果，包含支付表单
     */
    @PostMapping("/miniProgramPay")
    public Result miniProgramPay(@RequestParam("userId") Long userId,
                                @RequestParam("amount") Double amount) {
        // 检查参数
        if (amount <= 0) {
            return Result.error().message("充值金额必须大于0");
        }

        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }

        try {
            System.out.println("收到小程序支付请求，用户ID：" + userId + "，金额：" + amount);

            // 调用支付服务创建支付记录并获取支付表单
            String paymentServiceUrl = "http://alipay-service/alipay/miniProgramPay";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("userId", userId.toString());
            map.add("amount", amount.toString());
            map.add("subject", "充值余额");

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);

            System.out.println("准备调用支付服务：" + paymentServiceUrl);

            // 调用支付服务
            ResponseEntity<Map> response = restTemplate.postForEntity(paymentServiceUrl, requestEntity, Map.class);
            Map<String, Object> responseBody = response.getBody();

            System.out.println("支付服务响应：" + responseBody);

            if (responseBody != null && responseBody.containsKey("code") && (Integer)responseBody.get("code") == 200) {
                // 获取订单号和其他数据
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                String orderNo = data != null ? (String) data.get("orderNo") : "";
                String payForm = data != null ? (String) data.get("payForm") : "";

                return Result.ok()
                        .message("订单创建成功，请完成支付")
                        .data("orderNo", orderNo)
                        .data("amount", amount)
                        .data("payForm", payForm);
            } else {
                return Result.error().message("订单创建失败：" + (responseBody != null ? responseBody.get("msg") : "未知错误"));
            }
        } catch (Exception e) {
            System.err.println("创建支付订单失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error().message("创建支付订单失败：" + e.getMessage());
        }
    }

    /**
     * 主动查询支付结果并更新账户余额
     * @param orderNo 订单号
     * @return 查询结果
     */
    @PostMapping("/checkPaymentStatus")
    public Result checkPaymentStatus(@RequestParam("orderNo") String orderNo) {
        try {
            System.out.println("收到查询支付状态请求，订单号：" + orderNo);
            
            // 调用支付服务查询支付状态
            String paymentServiceUrl = "http://alipay-service/alipay/checkAndUpdatePayment";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("orderNo", orderNo);
            
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
            
            System.out.println("准备调用支付服务查询接口：" + paymentServiceUrl);
            
            // 调用支付服务
            ResponseEntity<Map> response = restTemplate.postForEntity(paymentServiceUrl, requestEntity, Map.class);
            Map<String, Object> responseBody = response.getBody();
            
            System.out.println("支付查询服务响应：" + responseBody);
            
            if (responseBody != null && responseBody.containsKey("code")) {
                int code = (Integer) responseBody.get("code");
                String msg = (String) responseBody.get("msg");
                
                if (code == 200) {
                    // 获取数据
                    Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                    if (data != null) {
                        String status = (String) data.get("status");
                        
                        if ("已支付".equals(status)) {
                            // 支付成功
                            return Result.ok()
                                    .message(msg)
                                    .data("orderNo", orderNo)
                                    .data("status", status)
                                    .data("amount", data.get("amount"));
                        } else {
                            // 未支付
                            return Result.ok()
                                    .message("订单未支付")
                                    .data("orderNo", orderNo)
                                    .data("status", status);
                        }
                    }
                }
                
                // 其他情况
                return Result.error()
                        .code(code)
                        .message(msg);
            } else {
                return Result.error().message("查询支付状态失败，返回数据异常");
            }
        } catch (Exception e) {
            System.err.println("查询支付状态异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error().message("查询支付状态异常：" + e.getMessage());
        }
    }

    /**
     * 测试支付宝沙箱支付，直接返回支付表单
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 包含支付表单HTML的结果
     */
    @PostMapping("/testAlipayForm")
    public String testAlipayForm(@RequestParam("userId") Long userId,
                                @RequestParam("amount") Double amount,
                                HttpServletResponse response) {
        try {
            // 检查参数
            if (amount <= 0) {
                response.setContentType("text/html;charset=UTF-8");
                return "<h1>充值金额必须大于0</h1>";
            }

            // 检查用户是否存在
            User user = userService.getById(userId);
            if (user == null) {
                response.setContentType("text/html;charset=UTF-8");
                return "<h1>用户不存在</h1>";
            }

            System.out.println("收到测试支付请求，用户ID：" + userId + "，金额：" + amount);

            // 调用支付服务创建支付记录并获取支付表单
            String paymentServiceUrl = "http://alipay-service/alipay/miniProgramPay";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("userId", userId.toString());
            map.add("amount", amount.toString());
            map.add("subject", "充值余额");

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);

            System.out.println("准备调用支付服务：" + paymentServiceUrl);

            // 调用支付服务
            ResponseEntity<Map> response1 = restTemplate.postForEntity(paymentServiceUrl, requestEntity, Map.class);
            Map<String, Object> responseBody = response1.getBody();

            System.out.println("支付服务响应：" + responseBody);

            if (responseBody != null && responseBody.containsKey("code") && (Integer)responseBody.get("code") == 200) {
                // 获取订单号和其他数据
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                String orderNo = data != null ? (String) data.get("orderNo") : "";
                String payForm = data != null ? (String) data.get("payForm") : "";

                // 设置响应类型为HTML
                response.setContentType("text/html;charset=UTF-8");
                
                // 构建HTML页面，包含支付表单和订单信息
                StringBuilder html = new StringBuilder();
                html.append("<!DOCTYPE html>");
                html.append("<html>");
                html.append("<head>");
                html.append("<title>支付宝沙箱支付测试</title>");
                html.append("<meta charset=\"UTF-8\">");
                html.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
                html.append("<style>");
                html.append("body { font-family: Arial, sans-serif; margin: 20px; }");
                html.append(".info { margin-bottom: 20px; padding: 10px; background-color: #f0f0f0; border-radius: 5px; }");
                html.append("</style>");
                html.append("</head>");
                html.append("<body>");
                html.append("<h1>支付宝沙箱支付测试</h1>");
                html.append("<div class=\"info\">");
                html.append("<p><strong>订单号：</strong>").append(orderNo).append("</p>");
                html.append("<p><strong>金额：</strong>").append(amount).append("</p>");
                html.append("</div>");
                html.append("<div id=\"payForm\">");
                html.append(payForm);
                html.append("</div>");
                html.append("<script>");
                html.append("document.addEventListener('DOMContentLoaded', function() {");
                html.append("  // 自动提交支付表单");
                html.append("  var form = document.querySelector('#payForm form');");
                html.append("  if (form) {");
                html.append("    form.submit();");
                html.append("  }");
                html.append("});");
                html.append("</script>");
                html.append("</body>");
                html.append("</html>");
                
                return html.toString();
            } else {
                response.setContentType("text/html;charset=UTF-8");
                return "<h1>订单创建失败：" + (responseBody != null ? responseBody.get("msg") : "未知错误") + "</h1>";
            }
        } catch (Exception e) {
            System.err.println("创建支付订单失败: " + e.getMessage());
            e.printStackTrace();
            response.setContentType("text/html;charset=UTF-8");
            return "<h1>创建支付订单失败：" + e.getMessage() + "</h1>";
        }
    }

    /**
     * 查询用户充值记录
     * 查询条件：用户ID和支付方式为"余额充值"
     * @param userId 用户ID
     * @return 充值记录列表
     */
    @GetMapping("/rechargeRecords")
    public Result getRechargeRecords(@RequestParam("userId") Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 查询充值记录
        List<Payment> records = userService.getRechargeRecords(userId);
        
        return Result.ok().data("records", records);
    }
    
    /**
     * 查询用户消费记录
     * 查询条件：用户ID和支付方式不为"余额充值"（包括微信支付、支付宝支付、余额支付等）
     * @param userId 用户ID
     * @return 消费记录列表
     */
    @GetMapping("/consumptionRecords")
    public Result getConsumptionRecords(@RequestParam("userId") Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 查询消费记录
        List<Payment> records = userService.getConsumptionRecords(userId);
        
        return Result.ok().data("records", records);
    }
    
    /**
     * 查询用户资金流水
     * 查询条件：仅用户ID，包含所有支付记录
     * @param userId 用户ID
     * @return 资金流水列表
     */
    @GetMapping("/paymentRecords")
    public Result getPaymentRecords(@RequestParam("userId") Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        
        // 查询资金流水
        List<Payment> records = userService.getPaymentRecords(userId);
        
        return Result.ok().data("records", records);
    }
}
